package com.dream.auth.util;

import java.io.FileOutputStream;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.util.Base64;

public class RSAKeyGenerator {
    public static void main(String[] args) throws Exception {
        // 生成RSA密钥对
        KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
        keyPairGenerator.initialize(2048);
        KeyPair keyPair = keyPairGenerator.generateKeyPair();

        // 获取私钥和公钥
        byte[] privateKeyBytes = keyPair.getPrivate().getEncoded();
        byte[] publicKeyBytes = keyPair.getPublic().getEncoded();

        // Base64编码
        String privateKeyStr = Base64.getEncoder().encodeToString(privateKeyBytes);
        String publicKeyStr = Base64.getEncoder().encodeToString(publicKeyBytes);

        // 添加PEM格式的头部和尾部
        String privatePem = "-----BEGIN PRIVATE KEY-----\n" +
                formatKey(privateKeyStr) +
                "\n-----END PRIVATE KEY-----";
        
        String publicPem = "-----BEGIN PUBLIC KEY-----\n" +
                formatKey(publicKeyStr) +
                "\n-----END PUBLIC KEY-----";

        // 保存到文件
        String resourcePath = "src/main/resources/keys/";
        Files.createDirectories(Paths.get(resourcePath));
        
        try (FileOutputStream privateOut = new FileOutputStream(resourcePath + "private.key")) {
            privateOut.write(privatePem.getBytes());
        }
        
        try (FileOutputStream publicOut = new FileOutputStream(resourcePath + "public.key")) {
            publicOut.write(publicPem.getBytes());
        }

        System.out.println("RSA密钥对已生成并保存到 " + resourcePath);
    }

    // 将Base64字符串按64个字符一行进行格式化
    private static String formatKey(String key) {
        StringBuilder formatted = new StringBuilder();
        int length = key.length();
        int lineLength = 64;
        
        for (int i = 0; i < length; i += lineLength) {
            int endIndex = Math.min(i + lineLength, length);
            formatted.append(key.substring(i, endIndex)).append("\n");
        }
        
        return formatted.toString().trim();
    }
} 